﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ConnectionLine : MonoBehaviour
{
    public RectTransform startCircle;
    public RectTransform endCircle;

    private RectTransform rectTransform;
    public Color color;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    public void Initialize(RectTransform start, RectTransform end)
    {
        startCircle = start;
        endCircle = end;
        SetColor(color);
        UpdateLinePosition();
    }

    private void Update()
    {
        if (startCircle != null && endCircle != null)
        {
            UpdateLinePosition();
        }
    }

    private void UpdateLinePosition()
    {
        Vector2 startPos = GetEdgePosition(startCircle, endCircle.anchoredPosition);
        Vector2 endPos = GetEdgePosition(endCircle, startCircle.anchoredPosition);

        rectTransform.anchoredPosition = (startPos + endPos) / 2f;
        rectTransform.sizeDelta = new Vector2(Vector2.Distance(startPos, endPos), rectTransform.sizeDelta.y);

        Vector2 direction = (endPos - startPos).normalized;
        rectTransform.localEulerAngles = new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
    }

    private Vector2 GetEdgePosition(RectTransform circle, Vector2 targetPos)
    {
        Vector2 direction = (targetPos - circle.anchoredPosition).normalized;
        return circle.anchoredPosition + direction * (circle.rect.width / 2f);
    }


    public void SetColor(Color color)
    {
        GetComponent<Image>().color = color;
    }
}
